<template>
  <div>
    <!-- 头部区域 -->
    <van-nav-bar title="黑马头条-登录" />
    <!-- 表单区域 -->
    <div>
      <van-form @submit="onSubmit">
        <van-field required v-model="user.mobile" name="mobile" label="手机号" placeholder="请输入11位手机号" :rules="[{ required: true,pattern: /^1[3-9]\d{9}$/, message: '请填写正确的手机号' }]" />
        <van-field required v-model="user.code" type="password" name="code" label="密码" placeholder="密码" :rules="[{ required: true, pattern: /\d{6}$/, message: '请填写6位的密码' }]" />
        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit" :loading="isLoading" loading-text="登录中..." :disabled="isLoading">登录</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import { loginApi } from '@/api/index'
import { setToken } from '@/utils/token.js'
import Notify from '@/ui/Notify.js'
import { setStorage } from '@/utils/storage'
export default {
  data() {
    return {
      user: {
        mobile: '13879652423',
        code: '246810'
      },
      isLoading: false // 登录中状态
    }
  },
  methods: {
    async onSubmit(values) {
      this.isLoading = true
      try {
        const res = await loginApi(values)
        Notify({ type: 'success', message: '登录成功啦!' })
        // 往本地存token
        setToken(res.data.data.token)
        // 往本地存refresh_token 用于刷新用户token
        setStorage('refresh_token', res.data.data.refresh_token)
        // 跳转到登录页(跳转尽量最后执行)
        this.$router.replace({
          path: this.$route.query.path || '/layout/home' // 从点赞页或者关注页跳来登录页会跳转到拿到的点赞页或者关注页的路由路径去 否则直接去主页
        })
      } catch (error) {
        Notify({ type: 'danger', message: '账号或密码错误' })
      }
      // 等网络请求完成后吧isLoading改为false
      this.isLoading = false
    }
  }
}
</script>

<style scoped lang="less">
.van-nav-bar {
  background-color: #007bff;
}
/deep/ .van-nav-bar__title {
  color: #fff;
}
</style>
